import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xterm/xterm.dart';
import '../models/ssh_connection.dart';
import '../models/command_history.dart';
import '../services/database_service.dart';
import '../services/ssh_service.dart';
import '../services/ai_service.dart';
import 'package:flutter/services.dart';

class TerminalScreen extends StatefulWidget {
  final SSHConnection connection;

  const TerminalScreen({super.key, required this.connection});

  @override
  State<TerminalScreen> createState() => _TerminalScreenState();
}

class _TerminalScreenState extends State<TerminalScreen> {
  late final Terminal terminal;
  late final TerminalController terminalController;
  final _commandController = TextEditingController();
  final _scrollController = ScrollController();
  
  List<CommandHistory> _commandHistory = [];
  bool _isExecuting = false;
  bool _isConnected = false;
  bool _isAIProcessing = false;
  String _systemType = 'Linux';
  final AIService _aiService = AIService();

  @override
  void initState() {
    super.initState();
    terminalController = TerminalController();
    terminal = Terminal(maxLines: 10000);
    
    _loadCommandHistory();
    _connect();
    _detectSystemType();
  }

  @override
  void dispose() {
    terminalController.dispose();
    _commandController.dispose();
    _scrollController.dispose();
    _disconnect();
    super.dispose();
  }

  Future<void> _detectSystemType() async {
    final sshService = context.read<SSHService>();
    try {
      final result = await sshService.executeCommand('uname -s');
      final osName = result.output.toLowerCase();
      
      setState(() {
        if (osName.contains('linux')) {
          _systemType = 'Linux';
        } else if (osName.contains('darwin')) {
          _systemType = 'macOS';
        } else if (osName.contains('windows')) {
          _systemType = 'Windows';
        } else {
          _systemType = 'Linux';
        }
      });
    } catch (e) {
      terminal.write('无法检测系统类型，使用默认Linux\r\n');
    }
  }

  Future<void> _loadCommandHistory() async {
    final databaseService = context.read<DatabaseService>();
    final history = await databaseService.getCommandHistory(widget.connection.id);
    setState(() {
      _commandHistory = history;
    });
  }

  Future<void> _connect() async {
    final sshService = context.read<SSHService>();
    
    try {
      terminal.write('正在连接到 ${widget.connection.host}:${widget.connection.port}...\r\n');
      
      final success = await sshService.connect(widget.connection);
      if (success) {
        terminal.write('连接成功！\r\n');
        setState(() {
          _isConnected = true;
        });
        
        await sshService.startShell(
          onOutput: (data) {
            terminal.write(data);
          },
        );
      } else {
        terminal.write('连接失败！\r\n');
      }
    } catch (e) {
      terminal.write('连接错误: $e\r\n');
    }
  }

  Future<void> _disconnect() async {
    final sshService = context.read<SSHService>();
    await sshService.disconnect();
    setState(() {
      _isConnected = false;
    });
    if (mounted) {
      Navigator.pop(context);
    }
  }

  // 修改 _executeCommand 方法
  Future<void> _executeCommand(String command) async {
    if (command.trim().isEmpty || !_isConnected) return;
    
    final sshService = context.read<SSHService>();
    
    setState(() {
      _isExecuting = true;
    });
    
    try {
      terminal.write('\$ $command\r\n');
      
      // 解析主命令名（空格前的部分）
      final mainCommand = command.trim().split(' ').first;
      
      // 检查命令是否存在
      final checkResult = await sshService.executeCommand('which "$mainCommand"');
      final commandExists = checkResult.output.trim().isNotEmpty && checkResult.exitCode == 0;
      
      if (commandExists) {
        // 命令存在，直接执行
        terminal.write('✅ 命令存在: ${checkResult.output.trim()}\r\n');
        await sshService.writeToShell(command);
      } else {
        // 命令不存在，使用AI分析
        terminal.write('⚠️ 命令不存在，使用AI分析...\r\n');
        await _executeAICommand(command);
      }
    } catch (e) {
      terminal.write('执行错误: $e\r\n');
    } finally {
      setState(() {
        _isExecuting = false;
      });
    }
  }

  // 修改 _executeAICommand 方法，添加命令存在性提示
  Future<void> _executeAICommand(String naturalCommand) async {
    if (naturalCommand.trim().isEmpty || !_isConnected) return;
    
    setState(() {
      _isAIProcessing = true;
    });
    
    try {
      terminal.write('🤖 AI正在解析命令: $naturalCommand\r\n');
      
      final commands = await _aiService.parseNaturalCommand(naturalCommand, _systemType);
      
      if (commands.isEmpty) {
        terminal.write('❌ AI未能解析出有效命令\r\n');
        return;
      }
      
      terminal.write('✅ AI解析出 ${commands.length} 条命令:\r\n');
      for (int i = 0; i < commands.length; i++) {
        terminal.write('  ${i + 1}. ${commands[i]}\r\n');
      }
      
      // 执行所有命令
      for (final command in commands) {
        terminal.write('\r\n🚀 执行: $command\r\n');
        
        // 对AI生成的命令也进行检查
        final mainCommand = command.trim().split(' ').first;
        final checkResult = await context.read<SSHService>().executeCommand('which "$mainCommand"');
        final commandExists = checkResult.output.trim().isNotEmpty && checkResult.exitCode == 0;
        
        if (commandExists) {
          await context.read<SSHService>().writeToShell(command);
        } else {
          terminal.write('⚠️ AI生成的命令 "$mainCommand" 不存在，跳过执行\r\n');
        }
        
        await Future.delayed(const Duration(milliseconds: 500));
      }
      
    } catch (e) {
      terminal.write('❌ AI命令解析失败: $e\r\n');
    } finally {
      setState(() {
        _isAIProcessing = false;
      });
    }
  }

  void _showCommandHistory() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('命令历史'),
        content: SizedBox(
          width: double.maxFinite,
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: _commandHistory.length,
            itemBuilder: (context, index) {
              final history = _commandHistory[index];
              return ListTile(
                title: Text(history.command),
                subtitle: Text(
                  '执行时间: ${history.executedAt.toString().substring(0, 19)}',
                ),
                onTap: () {
                  _commandController.text = history.command;
                  Navigator.pop(context);
                },
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.connection.name} ($_systemType)'),
        actions: [
          IconButton(
            icon: const Icon(Icons.content_copy),
            onPressed: () async {
              final buffer = terminal.buffer;
              String selectedText = '';
              
              if (terminalController.selection != null && !terminalController.selection!.isCollapsed) {
                final selection = terminalController.selection!;
                selectedText = buffer.getText(selection);
              }
              
              if (selectedText.isNotEmpty) {
                await Clipboard.setData(ClipboardData(text: selectedText));
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('已复制到剪贴板')),
                );
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('请先选择文本')),
                );
              }
            }
          ),
          IconButton(
            icon: const Icon(Icons.history),
            onPressed: _showCommandHistory,
          ),
          IconButton(
            icon: const Icon(Icons.close),
            onPressed: _disconnect,
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: TerminalView(
                terminal,
                controller: terminalController,
                autofocus: true,
              ),
            ),
          ),
          _buildCommandInput(),
        ],
      ),
    );
  }

  Widget _buildCommandInput() {
    return Container(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _commandController,
                  decoration: InputDecoration(
                    hintText: _isAIProcessing ? 'AI正在处理...' : '输入命令或描述...',
                    border: const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    prefixIcon: _isAIProcessing 
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: Padding(
                              padding: EdgeInsets.all(8.0),
                              child: CircularProgressIndicator(strokeWidth: 2),
                            ),
                          )
                        : const Icon(Icons.terminal),
                  ),
                  onSubmitted: (text) {
                    if (text.startsWith('ai:') || text.startsWith('AI:')) {
                      _executeAICommand(text.substring(3).trim());
                    } else {
                      _executeCommand(text);
                    }
                    _commandController.clear();
                  },
                  enabled: _isConnected && !_isAIProcessing,
                ),
              ),
              const SizedBox(width: 8),
              ElevatedButton(
                onPressed: _isConnected && !_isAIProcessing && _commandController.text.trim().isNotEmpty
                    ? () {
                        final text = _commandController.text;
                        if (text.startsWith('ai:') || text.startsWith('AI:')) {
                          _executeAICommand(text.substring(3).trim());
                        } else {
                          _executeCommand(text);
                        }
                        _commandController.clear();
                      }
                    : null,
                child: const Text('执行'),
              ),
            ],
          ),
          const SizedBox(height: 4),
          const Text(
            '提示: 输入 "ai: 描述" 使用AI命令解析',
            style: TextStyle(fontSize: 12, color: Colors.grey),
          ),
        ],
      ),
    );
  }
}

// 根据要求移除未被引用的 _TerminalBackend 类声明，同时移除相关实现代码
  // @override
  // Future<int> get exitCode => Completer<int>().future;

  // @override
  // void init() {}

  // @override
  // void resize(int width, int height) {}

  // @override
  // Stream<String> get out => const Stream.empty();

  // @override
  // void write(String input) {}

  // @override
  // void terminate() {}
